//
//  DMapViewController.m
//  dance
//
//  Created by aether on 2023/10/22.
//

#import "DMapViewController.h"
#import <MapKit/MapKit.h>

@interface DMapViewController () <CLLocationManagerDelegate, MKMapViewDelegate>

@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) CLLocation *currentLocation;
@property (nonatomic) CLLocationCoordinate2D destinationCoordinate;
@property (nonatomic, strong) MKAnnotationView *destinationView;
@property (nonatomic, strong) MKMapView *mapView;

@end

@implementation DMapViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self initNavi];
    [self initLocation];
    [self initSearch];
}

- (void) initNavi {
    // 创建右侧的UIBarButtonItem
    UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(rightButtonTapped:)];
    
    // 设置右侧按钮
    self.navigationItem.rightBarButtonItem = rightButtonItem;

}

- (void) initLocation {
    // 请求用户位置权限
    [self.locationManager requestWhenInUseAuthorization];
    [self.view addSubview:self.mapView];
}

- (void) initSearch {
    MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc] init];
    request.naturalLanguageQuery = @"广场"; // 搜索关键词，例如"餐馆"
    MKLocalSearch *localSearch = [[MKLocalSearch alloc] initWithRequest:request];

    [localSearch startWithCompletionHandler:^(MKLocalSearchResponse *response, NSError *error) {
        if (!error) {
            NSLog(@"有 = %lu", (unsigned long)response.mapItems.count);
            // 搜索成功，处理结果
            for (MKMapItem *mapItem in response.mapItems) {
                // 处理每个搜索结果
                NSString *name = mapItem.name;
                NSLog(@"NAME = %@", name);
                CLLocationCoordinate2D coordinate = mapItem.placemark.coordinate;
                // 可以将搜索结果显示在地图上或在列表中展示
                // 创建标注并添加到地图上
                MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
                annotation.coordinate = coordinate;
                annotation.title = name;
                [self.mapView addAnnotation:annotation];

            }
        } else {
            // 搜索出错，处理错误
            NSLog(@"搜索出错：%@", error.localizedDescription);
        }
    }];

}

- (void)searchPlazasNearUserLocation:(CLLocation *)userLocation {
    MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc] init];
    request.naturalLanguageQuery = @"广场"; // 搜索关键词，例如"广场"
    
    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 10000, 10000); // 10公里范围
    request.region = region;
    
    MKLocalSearch *localSearch = [[MKLocalSearch alloc] initWithRequest:request];
    
    [localSearch startWithCompletionHandler:^(MKLocalSearchResponse *response, NSError *error) {
        if (!error) {
            for (MKMapItem *mapItem in response.mapItems) {
                // 获取广场坐标和名称
                CLLocationCoordinate2D plazaCoordinate = mapItem.placemark.coordinate;
                NSString *plazaName = mapItem.name;
                
                // 创建标注并添加到地图上
                MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
                annotation.coordinate = plazaCoordinate;
                annotation.title = plazaName;
                [self.mapView addAnnotation:annotation];
            }
        } else {
            NSLog(@"搜索出错：%@", error.localizedDescription);
        }
    }];
}



- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    CLLocation *userLocation = [locations lastObject];
    self.currentLocation = userLocation;
    
    // 在这里可以获取用户的当前位置并进行相关操作
    [self updateMapWithUserLocation:userLocation];
    // 使用用户当前位置坐标执行搜索
    [self searchPlazasNearUserLocation:userLocation];
    
    // 停止获取用户位置
    [manager stopUpdatingLocation];
}

- (void)updateMapWithUserLocation:(CLLocation *)userLocation {
    // 清除地图上的所有标记
    [self.mapView removeAnnotations:self.mapView.annotations];
    
//    // 创建用户当前位置的标注
//    MKPointAnnotation *userAnnotation = [[MKPointAnnotation alloc] init];
//    userAnnotation.coordinate = userLocation.coordinate;
//    userAnnotation.title = @"您的位置";
//    [self.mapView addAnnotation:userAnnotation];
        
    // 设置地图显示区域，以确保用户位置和标记的广场都可见
    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 10000, 10000); // 10公里范围
    [self.mapView setRegion:region animated:YES];
}

#pragma mark - 代理方法

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
    if ([annotation isKindOfClass:[MKPointAnnotation class]]) {
        MKPinAnnotationView *pinView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:@"pinView"];
        if (!pinView) {
            pinView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"pinView"];
            pinView.canShowCallout = YES; // 显示标注的标题和描述
        } else {
            pinView.annotation = annotation;
        }
        return pinView;
    }
    return nil;
}

- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view {
    if ([view.annotation isKindOfClass:[MKPointAnnotation class]]) {
        self.destinationCoordinate = view.annotation.coordinate;
        
        self.destinationView = view;
        
        
    }
    
}

- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay {
    MKPolylineRenderer *renderer = [[MKPolylineRenderer alloc] initWithOverlay:overlay];
    renderer.strokeColor = [UIColor blueColor];
    renderer.lineWidth = 5.0;
    return renderer;
}

#pragma mark - 内部方法

- (void) rightButtonTapped:(UIBarButtonItem *) item {
    NSLog(@"索索");
    
    if (self.destinationView == NULL) {
        // 在此处显示导航按钮，例如，使用UIAlertController
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"导航" message:@"选择一个广场导航" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alertController animated:YES completion:nil];
    } else {
        
        // 在此处显示导航按钮，例如，使用UIAlertController
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"导航" message:[NSString stringWithFormat:@"是否开始导航到%@?", self.destinationView.annotation.title] preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"导航" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//            MKDirectionsRequest *directionsRequest = [[MKDirectionsRequest alloc] init];
//
//            // 设置起始点为用户的当前位置
//            MKPlacemark *sourcePlacemark = [[MKPlacemark alloc] initWithCoordinate:self.currentLocation.coordinate];
//            MKMapItem *sourceMapItem = [[MKMapItem alloc] initWithPlacemark:sourcePlacemark];
//            [directionsRequest setSource:sourceMapItem];
//
//            // 设置目的地为点击的标记的位置
//            MKPlacemark *destinationPlacemark = [[MKPlacemark alloc] initWithCoordinate:self.destinationCoordinate];
//            MKMapItem *destinationMapItem = [[MKMapItem alloc] initWithPlacemark:destinationPlacemark];
//            [directionsRequest setDestination:destinationMapItem];
//
//            // 选择导航模式
//            directionsRequest.transportType = MKDirectionsTransportTypeAutomobile; // 驾驶模式
//
//            MKDirections *directions = [[MKDirections alloc] initWithRequest:directionsRequest];
//            [directions calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse *response, NSError *error) {
//                if (!error) {
//                    MKRoute *route = [response.routes firstObject];
//                    // 获取导航路线，可以在地图上显示它
//                    [mapView addOverlay:route.polyline];
//                } else {
//                    NSLog(@"导航计算出错：%@", error.localizedDescription);
//                }
//            }];
            
            // 创建MKMapItem对象表示导航的目的地
            MKPlacemark *placemark = [[MKPlacemark alloc] initWithCoordinate:self.destinationView.annotation.coordinate];
            MKMapItem *destination = [[MKMapItem alloc] initWithPlacemark:placemark];
            destination.name = self.destinationView.annotation.title;
            
            // 设置导航选项
            NSDictionary *launchOptions = @{
                MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving, // 导航模式
                MKLaunchOptionsShowsTrafficKey: @YES // 是否显示交通信息
            };
            
            // 打开导航应用
            [MKMapItem openMapsWithItems:@[destination] launchOptions:launchOptions];

        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}

#pragma mark - 设置和获取

- (CLLocationManager *) locationManager {
    if (_locationManager == NULL) {
        self.locationManager = [[CLLocationManager alloc] init];
        self.locationManager.delegate = self;
        [self.locationManager startUpdatingLocation];
    }
    
    return _locationManager;
}

- (MKMapView *) mapView {
    if (_mapView == NULL) {
        self.mapView = [[MKMapView alloc] initWithFrame:self.view.bounds];
        self.mapView.showsUserLocation = YES;
        self.mapView.delegate = self;
    }
    
    return _mapView;
}

@end
